package com.yjz.study.ui.fragment

import android.os.Bundle
import android.util.SparseArray
import android.view.View
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentPagerAdapter
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.viewpager.widget.PagerAdapter
import androidx.viewpager.widget.ViewPager
import com.yjz.common.base.BaseFragment
import com.yjz.common.extend.showToast
import com.yjz.common.restful.CallBack
import com.yjz.common.restful.HttpBaseResponse
import com.yjz.study.R
import com.yjz.study.http.ApiFactory
import com.yjz.study.http.api.HomeApi
import com.yjz.study.http.entity.res.TabCategory
import com.yjz.study.viewmodel.HomeViewModel
import com.yjz.ui.tab.common.ITabLayout
import com.yjz.ui.tab.common.TabInfo
import com.yjz.ui.tab.top.TabTopLayout

/**
 *作用 : 首页
 *作者 : yjz
 *时间 : 2025/3/13 16:02
 */
class HomeFragment : BaseFragment() {

    private val topTabs = mutableListOf<TabInfo<Int>>()
    private var topTabTopLayout: TabTopLayout? = null
    private var viewPager: ViewPager? = null
    var defaultTabSelectIndex = 0

    override fun getLayoutId(): Int = R.layout.fragment_home

    companion object {
        fun newInstance(): Fragment {
            return HomeFragment()
        }
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        topTabTopLayout = view.findViewById(R.id.top_tab_layout)
        viewPager = view.findViewById(R.id.view_pager)

        val homeViewModel = ViewModelProvider(this)[HomeViewModel::class.java]
        homeViewModel.queryCategoryList().observe(viewLifecycleOwner) { tabs ->
            tabs?.let {
                updateUI(tabs)
            }
        }
    }

    private val onTabSelectedListener = ITabLayout.OnTabSelectedListener<TabInfo<*>> { index, _, _ ->
        if (viewPager?.currentItem != index) {
            viewPager?.setCurrentItem(index, false)
        }
    }

    private fun updateUI(data: List<TabCategory>) {
        if (isAlive) {
            // topTabs需要提到全局
            // 因为addOnPageChangeListener  在第一次设置的时候，他就绑定了一次的局部变量topTabs
            // 而再次刷新时，并没有 重新设置PageChangeListener，但是第一次的topTabs已经被释放了。
            topTabs.clear()
            val selectColor = resources.getColor(com.yjz.ui.R.color.tab_top_selected_color)
            val defaultColor = resources.getColor(com.yjz.ui.R.color.color_9b9)
            data.forEach { category ->
                topTabs.add(TabInfo(category.categoryName, selectColor, defaultColor))
            }
            topTabTopLayout?.addTabSelectChangeListener(onTabSelectedListener)
            topTabTopLayout?.inflateInfo(topTabs as List<TabInfo<*>>)
            topTabTopLayout?.defaultSelected(topTabs[defaultTabSelectIndex])

            if (viewPager?.adapter == null) {
                viewPager?.addOnPageChangeListener(object : ViewPager.SimpleOnPageChangeListener() {
                    override fun onPageSelected(position: Int) {
                        // 这个方法被触发有两种可能，第一种切换顶部tab  第二种 手动滑动翻页
                        // 如果是 手动滑动翻页人
                        if (position != defaultTabSelectIndex) {
                            defaultTabSelectIndex = position
                            topTabTopLayout?.defaultSelected(topTabs[position])
                        }
                    }
                })
                viewPager?.adapter = HomePagerAdapter(
                    childFragmentManager,
                    FragmentPagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT
                )
            }
            (viewPager?.adapter as HomePagerAdapter).update(data)
        }
    }

    inner class HomePagerAdapter(fm: FragmentManager, behavior: Int) : FragmentPagerAdapter(fm, behavior) {

        private val tabs = mutableListOf<TabCategory>()
        private val fragments = SparseArray<Fragment>(tabs.size)

        override fun getCount() = tabs.size

        override fun getItem(position: Int): Fragment {
            val categoryId = tabs[position].categoryId
            val categoryIdKey = categoryId.toInt()
            var fragment = fragments.get(
                categoryIdKey,
                null
            )
            /*根据position来复用不合理，position0 缓存中是热门，请求后position0 变为最新*/
            if (fragment == null) {
                fragment = HomeTabFragment.newInstance(tabs[position].categoryId)
                fragments.put(categoryIdKey, fragment)
            }
            return fragment
        }

        override fun getItemPosition(`object`: Any): Int {
            /*
             * 判断刷新前后fragment在viewpager中的位置是否改变
             * 改变了：none
             * 未改变：
             * 避免缓存的tab和新请求的tab一样，而fragment 先detach再通过getItem attach 重复生命周期浪费性能
             * 同时兼顾缓存的tab和新请求的tab不一样的情况
             * */
            val indexOfValue = fragments.indexOfValue(`object` as Fragment)
            val fragment = getItem(indexOfValue)/*刷新前的*fragment对象*/

            return if (fragment == `object`) PagerAdapter.POSITION_UNCHANGED else PagerAdapter.POSITION_NONE
        }

        /*位置对应的item，若会发生变化，都应该复写。默认返回position*/
        override fun getItemId(position: Int): Long {
            return tabs[position].categoryId.toLong()
        }

        fun update(list: List<TabCategory>) {
            tabs.clear()
            tabs.addAll(list)
            notifyDataSetChanged()
        }
    }
}